package com.legal.aid.app.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.legal.aid.app.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    public String uploadAvatar(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = ossConfig.getBasePath() + UUID.randomUUID().toString() + extension;

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(file.getContentType());
        metadata.setContentLength(file.getSize());

        PutObjectRequest putObjectRequest = new PutObjectRequest(
            ossConfig.getBucketName(),
            objectName,
            file.getInputStream(),
            metadata
        );

        ossClient.putObject(putObjectRequest);
        return ossConfig.getDomain() + objectName;
    }
} 